<template>
  <div id="feature-float"></div>
</template>

<script lang="ts" setup>
  import stomp from "../../../variable/Stomp";
  import * as echarts from "echarts";
  import {onMounted, onUnmounted} from "vue";
  import getThemeConfig from "@/variable/echarts";

  const props = defineProps<{
    id: string
  }>()

  const TYPES = ["max1s", "min1s", "max5s", "min5s", "max30s", "min30s", "avg3s", "avg60s"]
  const LABELS = ["1s最大值", "1s最小值", "5s最大值", "5s最小值", "30s最大值", "30s最小值", "3s平均值", "60s绝对均值"]

  const condition = {
    station: '',
    timeRange: 10,
    sample: 5,
    access: 1
  }

  let data = [];
  let myChart: any
  let option = getThemeConfig()
  const initEcharts = () => {
    const chartDom = document.getElementById('feature-float')
    if (chartDom == null) {
      return
    }
    chartDom.removeAttribute('_echarts_instance_')
    myChart = echarts.init(chartDom);
    myChart.setOption(option);
    window.addEventListener("resize", myChart.resize)
  }

  let seriesData = []
  const initSeriesData = () => {
    seriesData = []
    TYPES.forEach(() => {
      seriesData.push([])
    })
  }
  const loadData = () => {
    let oldAccess: number
    stomp.subscribe('/topic/fd', (message) => {

      if (message.id !== props.id) {
        return
      }
      if (!oldAccess || (oldAccess && oldAccess != condition.access)) {
        initSeriesData()
      }
      message.pcList.forEach((pc, index) => {
        if (index + 1 == condition.access) {
          TYPES.forEach((type, idx) => {
            seriesData[idx].push([message.timestamp * 1000, pc[type] * 1000])
            if (seriesData[idx].length > condition.timeRange) {
              seriesData[idx].splice(0, seriesData[idx].length - condition.timeRange)
            }
          })
        }
      })

      const series = []
      seriesData.forEach((data, idx) => {
        series.push({
          data: data,
          name: LABELS[idx],
          type: 'line',
          smooth: true,
          symbol: 'none'
        })
      })
      myChart.setOption({
        series,
        legend: {
          data: LABELS,
          left: '20%'
        }
      });
      oldAccess = condition.access
    });
  }


  onMounted(() => {
      initEcharts()
      initSeriesData()
      loadData()
  })

  onUnmounted(() => {
    window.removeEventListener("resize", myChart?.resize)
    stomp.unsubscribe('/topic/fd')
  })
</script>

<style scoped>
  #feature-float {
    width: 100%;
    height: 290px;
  }
</style>
